import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  // 计算属性
  const isLoggedIn = computed(() => {
    return !!(token.value && user.value)
  })

  const userName = computed(() => {
    if (!user.value) return '用户'
    
    // 兼容不同的数据结构
    const account = user.value.account || user.value
    
    return account?.accountName || account?.username || account?.name || '用户'
  })

  // 动作
  const login = (loginData) => {
    token.value = loginData.token
    user.value = loginData.user
    
    // 保存到本地存储
    localStorage.setItem('token', loginData.token)
    localStorage.setItem('user', JSON.stringify(loginData.user))
  }

  const logout = () => {
    token.value = ''
    user.value = null
    
    // 清除本地存储
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  const checkAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      user.value = JSON.parse(storedUser)
      return true
    }
    
    return false
  }

  return {
    // 状态
    token,
    user,
    
    // 计算属性
    isLoggedIn,
    userName,
    
    // 动作
    login,
    logout,
    checkAuth
  }
})
